package com.qf.service.impl;

import com.qf.dao.BookDao;
import com.qf.dao.impl.BookDaoImpl;
import com.qf.entity.Book;
import com.qf.entity.BookVo;
import com.qf.service.BookService;
import com.qf.utils.PageUtils;

import java.sql.SQLException;
import java.util.List;

public class BookServiceImpl implements BookService {
    private BookDao bookDao = new BookDaoImpl();

    @Override
    public PageUtils<Book> selectPage(BookVo bookVo, String currentPageNumStr, String pageSizeStr) {
        Integer currentPageNum;
        Integer pageSize;
        if (currentPageNumStr == null || "".equals(currentPageNumStr)) {
            currentPageNum = 1;
        } else {
            currentPageNum = Integer.valueOf(currentPageNumStr);
        }
        if (pageSizeStr == null || "".equals(pageSizeStr)) {
            pageSize = 4;
        } else {
            pageSize = Integer.valueOf(pageSizeStr);
        }

        List<Book> list;
        Integer totalCount;
        try {
            list = bookDao.selectPage(bookVo, currentPageNum, pageSize);
            totalCount = bookDao.getTotalCount(bookVo);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        Integer totalPageCount = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;

        PageUtils<Book> bookPage = new PageUtils<>();
        bookPage.setCurrentPageNum(currentPageNum);
        bookPage.setTotalPageCount(totalPageCount);
        bookPage.setTotalCount(totalCount);
        bookPage.setPageSize(pageSize);
        bookPage.setList(list);
        return bookPage;
    }

    @Override
    public int add(Book book) {
        try {
            return bookDao.add(book);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(Book book) {
        try {
            return bookDao.update(book);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int delete(String ids) {
        try {
            return bookDao.delete(ids);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Book selectBook(Integer bid) {
        try {
            return bookDao.selectBook(bid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
